package cn.edu.ahpu.utils;

import java.util.Stack;

/**
 * 将字符串运算式计算出结果并返回
 * @author Wildmess
 *
 */
public class Operate {

	/**
	 * 计算+、-、*、/运算符的四则运算
	 * @return
	 */
	public static float zeroToHundred(String equation) {
		/*数字栈*/
		Stack<Float> number = new Stack<Float>();
		/*字符栈*/
		Stack<Character> operation = new Stack<Character>();

		for (int i = 0; i < equation.length(); i++) {
			char c = equation.charAt(i);
			if(c=='+'||c=='-'||c=='*'||c=='/') {
				operation.push(c);
			}else{
				String str = "";
				while(true) {
					str += equation.charAt(i);
					if((i+1)!=equation.length()) {
						char ch = equation.charAt(i+1);
						if(ch=='+'||ch=='-'||ch=='*'||ch=='/') {
							break;
						}
					}else {
						break;
					}
					i++;
				}
				
				number.push(Float.valueOf(str));
				if(!operation.isEmpty()) {
					char oper = operation.peek();
					if(oper=='*'||oper=='/') {
						float count = Operate.operate(number.pop(), number.pop(), operation.pop());
						number.push(count);
					}
				}
			}
		}

		//此时，字符栈中不会再有*、/,只会剩下+、-
		while(!operation.isEmpty()) {
			float count = Operate.operate(number.pop(), number.pop(), operation.pop());
			number.push(count);
		}

		return number.pop();
	}

	/**
	 * 计算带有（）的整数四则运算
	 * @param equation
	 * @return
	 */
	public static Float withBracket(String equation) {
		Stack<Float> number = new Stack<Float>();
		Stack<Character> operation = new Stack<Character>();

		for (int i = 0; i < equation.length(); i++) {
			char c = equation.charAt(i);
			if(c==')') {
				String formula = "";
				while(operation.peek()!='(') {
					formula = operation.pop()+""+number.pop()+formula;
				}
				formula = operation.pop()+""+number.pop()+formula;
				//截取掉开头的（
				formula = formula.substring(1, formula.length());
				float count = Operate.zeroToHundred(formula);
				number.push(count);
			}else if(c=='+'||c=='-'||c=='*'||c=='/'||c=='(') {
				operation.push(c);
			}else if(c<=57 && c>=48) {
				number.push((float) (c-'0'));
			}
		}

		
		
		String endFormula = "";
		while(!operation.isEmpty()) {
			endFormula = operation.pop()+""+number.pop()+endFormula;
		}
		return Operate.zeroToHundred(number.pop()+endFormula);
	}
	public static float operate(Float x,Float y,Character oper) {
		switch(oper) {
		case '+':return x+y;
		case '-':return y-x;
		case '*':return x*y;
		case '/':return y/x;
		}
		return 0;
	}

	/**
	 * 封装常用的代码
	 * 
	 * 将数字栈和字符栈中的数据交替取出，生成字符串式子并返回
	 * @param number
	 * @param operation
	 * @return
	 */
	public static String toJointString(Stack<Integer> number, Stack<Character> operation) {
		String formula = "";
		
		boolean flag = true;
		while(!number.isEmpty()) {
			if(flag) {
				formula = ""+number.pop()+formula;
				flag = false;
			}else {
				formula = ""+operation.pop()+formula;
				flag = true;
			}
		}
		return formula;
	}
}
